<template>
  <el-dialog
    :visible.sync="isShow"
    width="600px"
    class="register"
    :show-close="false"
  >
    <div slot="title" class="title">用户注册</div>
    <el-form :model="form" label-width="80px" :rules="rules" ref="form">
      <el-form-item label="头像" class="uploadImg" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="gcode">
        <el-row>
          <el-col :span="14">
            <el-input v-model="form.gcode"></el-input>
          </el-col>
          <el-col :span="9" :offset="1">
            <img
              class="codeImg"
              @click="codeImgClick"
              :src="baseUrl + gcodeUrl"
              alt=""
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="14">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="9" :offset="1">
            <el-button @click="getcode" :disabled="totalTime != 5">
              获取用户验证码<span v-if="totalTime != 5"
                >({{ totalTime }}s)</span
              >
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <span slot="footer" class="footer">
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getPhoneCode,toRegister } from '@/api/register.js'
export default {
  watch:{
    "isShow"(newVal){
      if(newVal==false){
        this.$refs.form.resetFields();
      }
    }
  },
  data () {
    return {
      totalTime: 5,
      isShow: false,
      baseUrl: process.env.VUE_APP_URL,
      imageUrl: '',
      gcodeUrl: '/captcha?type=sendsms',

      form: {
        avatar: '',
        username: '',
        email: '',
        phone: '',
        password: '',
        gcode: '',
        rcode: ''
      },
      rules: {
        avatar: [
          {
            required: true,
            message: '请上传头像',
            trigger: 'change'
          }
        ],
        username: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'change'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请正确输入邮箱'))
              }
            }
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请正确输入手机号'))
              }
            }
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'change'
          }
        ],
        gcode: [
          {
            required: true,
            message: '请输入图形码',
            trigger: 'change'
          }
        ],
        rcode: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    handleAvatarSuccess (res,file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      //   console.log(file);
      this.form.avatar = res.data.file_path
      console.log(this.form.avatar)
      //   this.$refs.form.validateField(['avatar'])
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submit () {
      this.$refs.form.validate(result => {
        if (result) {
          // 验证成功后调用注册接口
          toRegister(this.form).then(res=>{
            console.log(res);
            this.isShow= false;
            this.$message.success('注册成功')
          })
        } else {
          this.$message.error('验证失败')
        }
      })
    },
    codeImgClick () {
      // 点击图片时切换图形码,在接口地址后面加个随机数或者时间戳就可以了
      this.gcodeUrl = '/captcha?type=sendsms&dgfeg=' + Date.now()
    },
    getcode () {
      let num = 0
      // 点击获取验证码时局部验证手机号和图形码
      this.$refs.form.validateField(['phone', 'gcode'], error => {
        if (error == '') {
          num++;
        }
      })
      if (num == 2) {
        // 当num为2时说明两个验证都通过了
        // this.$axios({
        //   url: '/sendsms',
        //   method: 'post',
        //   data: {
        //     code: this.form.gcode,
        //     phone: this.form.phone
        //   }
        // })
        this.totalTime--;
        let _setInterval= setInterval(()=>{
          this.totalTime--;
          if(this.totalTime==0){
            this.totalTime = 5;
            clearInterval(_setInterval)
          }
        },1000)
        getPhoneCode({
          code: this.form.gcode,
          phone: this.form.phone
        }).then(res => {
          console.log(res)
          this.$message.success(res.data.data.captcha+ '')
        }).catch(err=>{
          console.log(err);
        })
      } else {
        this.$message.error('请输入手机号和图形码')
      }
    }
  }
}
// 明天预习 :  1:调用接口验证码错误   a:验证码的图片地址搞错  (注册使用了登陆验证码地址,接口地址后面拼接参数错了   v地址?xxx=1&dfhdfh=随机数)    b:浏览器不要全用谷歌最新的建议使用双核   c需要加一个跨域带cookie   withCredentials:true(l加入到axios配制里面 )   4:传参有问题
</script>
<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    background: linear-gradient(#1493fa, #01c6fa);
    font-size: 14px;
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 400;
    text-align: center;
    color: #fefefe;
    letter-spacing: 0px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader {
    margin-left: 110px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .codeImg {
    width: 100%;
    height: 40px;
  }
  .footer {
    text-align: center;
    display: block;
  }
}
</style>
